package com.flying.framework.async.simple;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.flying.common.log.Logger;
import com.flying.common.util.ServiceHelper;
import com.flying.framework.async.Processor;
import com.flying.framework.data.Data;
import com.flying.framework.exception.AppException;

public class WithResultInThreadPool implements Processor{
	private static Logger logger = Logger.getLogger(WithResultInThreadPool.class);
	private static ExecutorService threadPool = Executors.newFixedThreadPool(50);

	@Override
	public Data process(String moduleId, String serviceId, Data data, TimeUnit waitTimeUnit, Long waitTime) {
		Future<Data> future = threadPool.submit(new EventCallable(moduleId, serviceId, data, waitTimeUnit, waitTime));
		try {
			return future.get();
		} catch (Exception e) {
			throw new AppException(e);
		}
	}
	
	class EventCallable implements Callable<Data> {
		private final String moduleId;
		private final String serviceId;
		private final Data data;
		private final Long createTime = System.currentTimeMillis();
		private final TimeUnit waitTimeUnit;
		private final Long waitTime;
		
		EventCallable(String moduleId, String serviceId, Data data, TimeUnit unit, Long waitTime) {
			this.moduleId = moduleId;
			this.serviceId = serviceId;
			this.data = data;
			this.waitTimeUnit = unit;
			this.waitTime = waitTime;
		}
		
		@Override
		public Data call() throws Exception {
			try {
				Long ms = waitTimeUnit.toMillis(waitTime);
				Thread.sleep(ms);
			} catch(Exception e) {
			}
			return ServiceHelper.invoke(moduleId, serviceId, data);
		}
		
	}
}
